(function(window, angular, undefined) {'use strict';
	var app = angular.module('kingDirectives', [])
	.directive('menu', function(){
	    return {
	        restrict: 'A',
	        scope: true,
	        link: function(scope, elem, attrs){
	            var data = scope.$eval(attrs['menu'])
	            scope.dirs = data
	            
	            function clearActive(jump){
	                $.each(scope.dirs, function(index, dir){
	                    if(dir !== jump && dir.active){
	                        delete dir.active
	                        return false;
	                    }
	                })
	            }
	            $.each(scope.dirs, function(index, dir){
    	            scope.$watch('dirs[' + index + '].active', function(newValue, oldValue){
    	                if(newValue){
    	                    clearActive(dir)
    	                }
    	            })
    	        })
	        },
	        templateUrl: '/js/apps/main/tpl/menu.html'
	    }
	})
	.directive('dir', ['$location', function($location){
	    return {
	        restrict: 'A',
	        scope: true,
	        link: function(scope, elem, attrs){
	            function inactivateDir(){
    	            clearActive()
    	            delete scope.dir.active
	            }
	            function clearActive(){
	                if(!scope.dir.children || !scope.dir.children.length) 
	                    return false;
	                $.each(scope.dir.children, function(index, child){
	                    if(child.active){
	                        delete child.active
	                        return false;
	                    }
	                })
	            }
                var toggleVisibility = function(){
                    elem.find('.dir-body').toggle()
                }
	            scope.clickHead = function(){
	                if(!scope.dir.children || !scope.dir.children.length){
	                    scope.dir.active = true
	                    var url = typeof scope.dir.url === 'string'
	                        ? scope.dir.url 
	                        : scope.dir.url() // 若非函数则报错
	                    $location.path(url)
	                } else {
	                    toggleVisibility()
	                }
	            }
	            scope.checkItem = function(item){
	                if(!scope.dir.active) scope.dir.active = true
	                if(!scope.dir.children || !scope.dir.children.length)
	                    return false;
	                clearActive()
	                item.active = true
	                var url = typeof item.url === 'string'
                        ? item.url 
                        : item.url() // 若非函数则报错
	                $location.path(url)
	            }
	            // 通过$watch来与上层交互，应该考虑使用事件
	            scope.$watch('dir.active', function(newValue, oldValue){
	                if(oldValue && !newValue){
	                    inactivateDir()
	                }
	            })
	        },
	        templateUrl: '/js/apps/main/tpl/dir.html'
	    }
	}])
	.directive('dropMenu', function(){
	    return {
	        restrict: 'A',
	        link: function(scope, elem, attrs){
    	        var menu = elem.find('.dropMenu')
	            elem.find('.trigger').on('click', function(){
	                menu.toggle()
	            })
	            elem.on('click', '.close', function(){
	                menu.hide()
	            })
	        }
	    }
	})
	.directive('datePicker', function(){
	    return {
	        link: function(scope, elem, attrs){
                // 暂时未找到改变输出格式的方法
                function date2str(dateObj){
                    var y = dateObj.getFullYear(),
                        m = dateObj.getMonth() + 1,
                        d = dateObj.getDate()
                    if(m<10) 
                        m = '0' + m
                    if(d<10)
                        d = '0' + d
                    return y+'-'+m+'-'+d
                }
	            var obj = {
	                begin: {
	                    datePicker: elem.find("#begin_datepicker"),
	                    input: $('.begin_time input')
	                },
	                end: {
	                    datePicker: elem.find("#end_datepicker"),
                        input: $('.end_time input')
	                }
	            }
	            var byFn = true // 区分控件输入与"最近n天的输入"
                $.each(obj, function(type, value){
                    value.datePicker.datepicker({
                        inline: true,
                        changeMonth: true,
                        changeYear: true,
                        showWeek: true,
                        maxDate: -1,
                        dateFormat: 'yy-mm-dd',
                        onSelect: function(dateStr){
                            scope.intervalCalendar[type].dateStr = dateStr
                            value.input.val(dateStr)
                            byFn = false
                            scope.$digest()
                        }
                    });
                    var datePicker = value.datePicker,
                        input = value.input
                    var date = date2str(datePicker.datepicker('getDate'))
                    scope.intervalCalendar[type].dateStr = date
                    input.on('blur', function(){
                        // 用户输入
                        var date = input.val()
                        scope.intervalCalendar[type].dateStr = date
                        datePicker.datepicker('setDate', new Date(date))
                        byFn = false
                        scope.$digest()
                    })
                    scope.$watch('intervalCalendar.' + type + '.dateStr', function(newValue, oldValue){
                        if(newValue === oldValue || newValue === undefined)
                            return false;
                            
                        obj[type].input.val(newValue)
                        if(!byFn){
                            scope.currentInterval = 0
                        }
                    })
                })
                scope.currentInterval = 30 // 默认30天
                function createDayFn(num){
                    return function(){
                        var t = 86400000
                        var yesterdayNumber = new Date(new Date() - t * 1)
                        var beginDate = new Date(yesterdayNumber - t*(num-1)),
                            endDate = new Date(yesterdayNumber)
                        $.each(['begin', 'end'], function(index, value){})
                        obj['begin'].datePicker.datepicker('setDate', beginDate)
                        obj['end'].datePicker.datepicker('setDate', endDate)
                        var beginDateStr = date2str(beginDate),
                            endDateStr = date2str(endDate)
                        obj['begin'].input.val(beginDateStr)
                        obj['end'].input.val(endDateStr)
                        scope.intervalCalendar['begin'].dateStr = beginDateStr
                        scope.intervalCalendar['end'].dateStr = endDateStr
                        scope.currentInterval = num
                        byFn = true
                    }
                }
                scope.intervalFns = {}
                $.each([7, 30, 90], function(index, num){
                    scope.intervalFns[num] = createDayFn(num)
                })
                scope.intervalFns[scope.currentInterval]()
                $(document).click(function(e){
                    // 隐藏其父元素
                    var parent = elem.parent('.dropMenu')
                    if(parent.css('display') === 'none') return ;
                    var obj = $(e.target);
                    if ($(obj).is(parent.siblings('.trigger')) || $(obj).is(parent.siblings('.trigger').children()) || $(obj).is(elem) || $(obj).is(elem.find('*'))) {
                        
                    } else {
                        parent.hide()
                    }
                });
	        }
	    }
	})
        .directive('widthFixed', function(){
            return {
                link: function(scope, elem, attrs){
                    var document_elem = $(document),
                        oldDocWidth 
                    elem.width(attrs['widthFixed'])
                    oldDocWidth = document_elem.width()
                    elemWidth = elem.css('width', '100%')
                    var elemWidth = elem.width()
                    if(oldDocWidth > elemWidth){
                        elem.css('width', oldDocWidth)
                    }
                    $(window).on('resize.widthFixed', function(event){handle()})
                    scope.$on('$destroy', function(){
                        $(window).off('resize.widthFixed')
                    })
                    function handle(){
                        var document_width = document_elem.width()
                        if(oldDocWidth != document_width){
                            elem.css('width', '100%')
                            oldDocWidth = document_width
                        }
                        else {
                            elem.width(document_width)
                        } 
                    }
                }
            }
        })
        .directive('ksPaging', ['$log', function($log){
            function link(scope, element, attr){
                //$log.debug('>>>ksPaging Link');
                element.addClass('ks-paging');

                var render = function(p){
//                    var size = scope.$eval(attr['totalSize']);
//                    var per = scope.$eval(attr['perPage']);
                    var size = scope.totalSize;
                    var per = scope.perPage;
                    var showPageIndexCount = 5;//中间页码数
                    scope.pageNum = Math.ceil(size/per);
                    scope.pages = [];
                    scope.curPage = p;

                    var start = p - 2;//中间页码开始页
                    var end = p + 2;//中间页码结束页

                    if(scope.pageNum == 0) return;

                    scope.prevPage = scope.curPage-1;
                    scope.nextPage = scope.curPage+1;
                    if(scope.nextPage>scope.pageNum-1) scope.nextPage = -1;
                   /* for(var i= 0; i<scope.pageNum; i++){
                        scope.pages.push(i);
                    }*/
                    
                    if (scope.pageNum <= showPageIndexCount + 1) {
                        for (var i = 0; i < scope.pageNum; i++) {
                            scope.pages.push(i);
                        }
                    } else {
                        if (start <= 0) {
                             for (var i = 0; i < showPageIndexCount; i++) {
                                scope.pages.push(i);
                            }
                            scope.pages.push('...', scope.pageNum - 1);
                        }
                        if (start >0 && end < scope.pageNum - 1) {
                            start ==1 ? scope.pages.push(0) : scope.pages.push(0,'...');
                            for (var i = start; i <= end; i++) {
                                scope.pages.push(i);
                            }
                            end == scope.pageNum - 2 ? scope.pages.push(scope.pageNum - 1) : scope.pages.push('...', scope.pageNum - 1);
                            
                        }
                        if(end >= scope.pageNum -1){
                            scope.pages.push(0, '...');
                            for(var i=scope.pageNum - 5; i < scope.pageNum; i++ ){
                                scope.pages.push(i);
                            }
                        }
                    }
                    $log.debug('Page Num:', scope.pageNum, scope.pages, scope.curPage, start, end);
                };


                scope.onClick = function(p){
                    if(p<0||p == scope.curPage) return false;
                    render(p);
                    return true;
                };

                scope.$watch('totalSize', function () {
                    render(0);
                }, true);

                scope.$watch('perPage', function () {
                    render(0);
                }, true);
            }
            return {
                scope: {
                    curPage: '=curPage',
                    totalSize: '=totalSize',
                    perPage: '=perPage'
                },
                templateUrl: '/js/apps/main/tpl/get-pagination.html?v=20151021',
                link: link
            };
        }])
    .directive('ksDatePicker2', [function() {
        return {
            restrict: 'A',
            scope: true,
            templateUrl: '/js/apps/main/tpl/calendar.html?v=20161103',
            link: function(scope, elem, attrs) {
                scope.week = ['日', '一', '二', '三', '四', '五', '六']
                scope.$watch(attrs['ksDatePicker2'], function(newValue, oldValue, scope) {
                    if(!newValue && newValue === oldValue) return false;
                    scope.dates = newValue.dates
                })
            }
        }
    }])
    .directive('singleCalendar', ['Calendar', function(Calendar){
        return {
            restrict: 'A',
            scope: true,
            templateUrl: '/js/apps/main/tpl/singleCalendar.html?v=20161103',
            link: function(scope, elem, attrs){
                function changeCalendarMonth(difference) {
                    var year = this.showedYear,
                        month = this.showedMonth + difference
                    if(month < 0 || month > 11) {
                        year += Math.floor(month / 12)
                         month = (month < 0 ? 12 : 0) + month % 12
                    }
                    this.setTime(year, month)
                }
                
                var settings = scope.$eval(attrs['singleCalendar'])
                var calendar = new Calendar(settings.year, settings.month, settings.settings)
                calendar.changeCalendarMonth = changeCalendarMonth
                calendar.prev = function() {
                    this.changeCalendarMonth(-1)
                }
                calendar.next = function() {
                    this.changeCalendarMonth(1)
                }
                void function(){
                    var select = calendar.select
                    calendar.select = function(){
                        // 只能选择单个
                        this.unselectAll()
                        return select.apply(this, arguments)
                    }
                    var selectDate = calendar.selectDate
                    calendar.selectDate = function(dateNum){
                        if(!this.getShowedDate(dateNum).available) return false;
                        return selectDate.apply(this, arguments)
                    }
                }()
                elem.on('click', '.dates .date', function(event){
                    var date = $(event.currentTarget)
                    if(date.hasClass('invalid'))
                        return ;
                    var value = parseInt(date.html())
                    scope.$apply(function(){
                        calendar[date.hasClass('selected') ? 'unselect' : 'select']([value])
                    })
                })
                scope.calendar = calendar
                scope.dates = calendar.dates
                if(typeof settings.getCalendar == 'function')
                    settings.getCalendar(calendar)
                settings.callback && settings.callback(calendar)
            }
        }
    }])
    void function(app){
        var link = function(attr, orderBy){
            return function(scope, elem, attrs){
                var settings = scope.$eval(attrs[attr])
                for(var i in settings){
                    scope[i] = settings[i]
                }
                scope.order = function(key){
                    if(key === scope.orderKey){
                        scope.reverse = !scope.reverse
                    }
                    scope.orderKey = key
                    orderBy(scope.data, key, null, scope.reverse)
                }
                scope.$watch('data', function(newValue, oldValue, scope){
                    if(newValue === oldValue) return false;
                    scope.vm.curPage = 0
                    orderBy(scope.data, scope.orderKey, null, scope.reverse)
                })
            }
        }
        app.directive('ksTable', ['orderBy', function(orderBy){
            return {
                restrict: 'A',
                scope: true,
                templateUrl: '/js/apps/main/tpl/ks-table.html?v=20161109',
                link: link('ksTable', orderBy)
            }
        }])
        .directive('ksTableCompany', ['orderBy', function(orderBy){
            return {
                restrict: 'A',
                scope: true,
                templateUrl: '/js/apps/main/tpl/ks-table-company.html?v=20161109',
                link: link('ksTableCompany', orderBy)
            }
        }])
        
    }(app)
})(window, window.angular);